package com.hxl.demo.controller;

import com.hxl.demo.entity.User;
import com.hxl.demo.service.Impl.UserServiceImpl;
import com.hxl.demo.tools.Common;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/admin")
public class LoginController {



    @Resource
    UserServiceImpl userServiceImpl;

    @RequestMapping("/login")
    public Object login(
            @RequestParam(value = "name") String name,
            @RequestParam(value = "pwd") String pwd,
            HttpServletRequest request) {
        String password=DigestUtils.md5DigestAsHex(pwd.getBytes());
        List<User> user=userServiceImpl.getUserByNameAndPassword(name,password );

//        判断用户是否已存在，如不存在直接注册
        // 登录认证，认证成功后将用户信息放到session中
        if (user.size()>0) {
            request.getSession().setAttribute("userInfo",  user.get(0).getStaffId());
            return Common.returnJsonFail("登录成功",200);

        }else{
//            User userAdd=new User();
//            userAdd.setUsername(name);
//            userAdd.setPassword(password);
//            userAdd.setInsertTime(new Date());
//
//            Integer id=userServiceImpl.userAddByNameAndPassword(userAdd);
//            request.getSession().setAttribute("userInfo", name + " - " + pwd);
//            if(id>0){
//                request.getSession().setAttribute("userInfo", id);
//                return Common.returnJsonFail("登录成功",200);
//            }
            return Common.returnJsonFail("登录失败",400);
        }


    }
}
